//
//  DHConfirmIDController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/15.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHConfirmIDController.h"

@interface DHConfirmIDController ()<UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *IDButtons;

@property(nonatomic ,strong)UIButton *currentButton;
@property(nonatomic,strong) UIImagePickerController *imagePicker; //声明全局的UIImagePickerController
@end

@implementation DHConfirmIDController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setupNav];
}
- (void)setupNav
{
    self.title = @"身份验证";
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:252.0f/255.0f green:62.0f/255.0f blue:8.0f/255.0f alpha:1];
}
- (IBAction)IDButtonClick:(UIButton *)sender
{
    self.currentButton.selected = false;
    sender.selected = YES;
    self.currentButton = sender;
    //自定义消息框
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    sheet.tag = 2550;
    //显示消息框
    [sheet showInView:self.view];
}
#pragma mark -消息框代理实现-
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 2550) {
        NSUInteger sourceType = 0;
        // 判断系统是否支持相机
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            imagePickerController.delegate = self; //设置代理
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = sourceType; //图片来源
            if (buttonIndex == 0) {
                //拍照
                sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
           

            }else if (buttonIndex == 1) {
                //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
     
            }else if (buttonIndex == 2){
                
                return;
            }
        }else {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
    }
}

#pragma mark -- 上传头像Data
- (NSString*)returnFielName{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat =@"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
    return fileName;
}
- (void)postUserImageFormDate{
    
//    NSString * sexString =[self.sexSelectButton.titleLabel.text isEqualToString:@"男"]?@"1":@"0";
//
//    NSDictionary *dict = @{@"key":[UserManager shareUser].key, @"mobile":self.phoneTextField.text,@"level_id":self.VIP_id,@"level_name":self.rankTextField.text,@"tuijian_member_name":self.recommenTextField.text,@"auth_name":self.realNameTextField.text,@"auth_card":self.idCarTextField.text,@"auth_sex":sexString};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/plain", nil];
    //正面照
    NSData *imgData1 = nil;
    imgData1 =UIImageJPEGRepresentation([self.IDButtons.firstObject currentImage],1);
    if ([imgData1 length]/1024<=100) {
        imgData1 =UIImageJPEGRepresentation([self.IDButtons.firstObject currentImage],1);
        
    }else{
        
        imgData1 =UIImageJPEGRepresentation([self compressImage:[self.IDButtons.firstObject currentImage] toByte:100*1024],0.5);
    }
    //反面照
    NSData *imgData2 = nil;
    
    imgData2 =UIImageJPEGRepresentation([self.IDButtons[1] currentImage],1);
    if ([imgData2 length]/1024<=100) {
        imgData2 =UIImageJPEGRepresentation([self.IDButtons[1] currentImage],1);
        
    }else{
        
        imgData2 =UIImageJPEGRepresentation([self compressImage:[self.IDButtons[1] currentImage] toByte:100*1024],0.5);
    }
    // 手持照
    NSData *imgData3 = nil;
    
    imgData3 =UIImageJPEGRepresentation([self.IDButtons.lastObject currentImage],1);
    if ([imgData3 length]/1024<=100) {
        imgData3 =UIImageJPEGRepresentation([self.IDButtons.lastObject currentImage],1);
        
    }else{
        
        imgData3 =UIImageJPEGRepresentation([self compressImage:[self.IDButtons.lastObject currentImage] toByte:100*1024],0.5);
    }
    NSArray *nameArray = @[@"id_card_img",@"auth_fm_imgurl",@"auth_sc_imgurl"];
    [manager POST:@"http://jpjd.cnaite.cn/mobile/index.php?act=member_index&op=member_info_auth"
       parameters:self.postParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
           
           
           
           [formData appendPartWithFileData:imgData1
                                       name:nameArray[0]
                                   fileName:[self returnFielName]
                                   mimeType:@"image/jpeg"];
           [formData appendPartWithFileData:imgData2
                                       name:nameArray[1]
                                   fileName:[self returnFielName]
                                   mimeType:@"image/jpeg"];
           [formData appendPartWithFileData:imgData3
                                       name:nameArray[2]
                                   fileName:[self returnFielName]
                                   mimeType:@"image/jpeg"];
           
           
           
       } progress:nil
          success:^(NSURLSessionTask *task, id responseObject) {
              
              //  NSString * errorStr;
              id temp = responseObject[@"datas"];
              
              if (temp[@"succ"]) {
//                  [XHToast showBottomWithText:@"提交成功" duration:2];
//                  [self checkTheApplyStatus];
                  [SVProgressHUD showSuccessWithStatus:temp[@"succ"]];
                  [self.navigationController popToRootViewControllerAnimated:true];
              }
              
              
          }
     
          failure:^(NSURLSessionTask *task, NSError *error) {
              NSLog(@"error:%@", error);
              
              
              
          }];

    
}
#pragma mark: - 压缩图像
- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    
    
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    
    UIImage *resultImage = [UIImage imageWithData:data];
    
    if (data.length < maxLength)
        
        return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        
    }
    
    return resultImage;
}
#pragma mark: - 保存并认证按钮监听
- (IBAction)saveButtonClick:(UIButton *)sender
{
    NSMutableArray *arrayIDImg = [NSMutableArray array];
    [self.IDButtons enumerateObjectsUsingBlock:^(UIButton *btn, NSUInteger idx, BOOL * _Nonnull stop) {
        if (btn.currentImage) {
            [arrayIDImg addObject:btn.currentImage];
        }
    }];
    
    if (arrayIDImg.count < 3) {
        [SVProgressHUD showInfoWithStatus:@"请完善您的资料"];
        return;
    }
    
    [self postUserImageFormDate];

}
#pragma mark -实现图片选择器代理-（上传图片的网络请求也是在这个方法里面进行，这里我不再介绍具体怎么上传图片）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //通过key值获取到图片

    //上传图片到服务器--在这里进行图片上传的网络请求，这里不再介绍
  //  ......
    [[self.IDButtons valueForKey:@"selected"] enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         if (obj.boolValue) {
             [(UIButton *)self.IDButtons[idx] setImage:image forState:UIControlStateNormal];
         }
     }];
}
@end
